//
//  WHOAuthViewController.swift
//  microblog
//
//  Created by Apple on 15/11/26.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

import SVProgressHUD

class WHOAuthViewController: UIViewController {

    override func loadView() {
        //不用设置约束
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权
        let request = NSURLRequest(URL: WHNetwrokTool.sharedInstance.oauthUrl())
        webView.loadRequest(request)
        
        //设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }

    //填充方法
    func autofill() {
        //创建js代码
        let js  = "document.getElementById('userId').value='15078157664@sina.cn'; document.getElementById('passwd').value='wrfhyx21@@';"
        //执行
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //取消方法
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //加载AccessToken
    func loadAccessToken(code: String) {
        //发送网络请求
        WHNetwrokTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            
            //判断
            if error != nil || result == nil {
                SVProgressHUD.showErrorWithStatus("网络睡着了。。。。",maskType: SVProgressHUDMaskType.Black)
                //进行关闭操作
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return
            }
            
            //没有出错
            print("result2: \(result)")
            //创建模型
            let userAccount = WHUserAccount(dict: result!)
            
            //保存对象
            //NSHomeDirectory()
            userAccount.saveAccount()
            print("userAccount:\(userAccount)")
            }
        }
    //懒加载
    private lazy var webView = UIWebView()

}

//使用代理，用来监听 实现 UIWebViewDelegate 协议
extension WHOAuthViewController: UIWebViewDelegate{
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)
    }
    /// webView加载完成某个链接
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // webView加载链接,每当webView加载一个链接都会通过这个代理方法来询问我们这个地址是否可以加载 true表示可以加载, false 就不加载.
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //绝对路径absoluteString
        let urlString = request.URL!.absoluteString
        //print("urlString:\(urlString)")
        //判断
        if !urlString.hasPrefix(WHNetwrokTool.sharedInstance.redirect_uri){
            
            return true
        }
        //点击取消或者是授权
        if let query = request.URL?.query{
            let codeString = "code="
            if query.hasPrefix(codeString) {
                //肯定是点击了授权
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("code=\(code)")
                // 加载accessToken
                loadAccessToken(code)
            }
        }
        return false
    }
}

